package com.controller;

import com.alibaba.fastjson.JSONArray;
import com.entity.Book;
import com.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @Author：李刚
 * @Date： 2020/12/9-9:38
 * @Description：
 */
@RestController
@CrossOrigin
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/all")
    public String findAll(){
        List<Book> bookList = redisTemplate.opsForList().range("books",0,-1);
        System.out.println("缓存中数据："+bookList.size());
        if(bookList.size()==0){
            System.out.println("=========缓存中没有数据,直接到数据库中查询==========");
            bookList = bookService.findAll();
        }else{
            System.out.println("==============缓存中有数据了==============");
            bookList.forEach(System.out::println);
        }
        return JSONArray.toJSONString(bookList);
    }

    @PostMapping("/insert")
    public String addBook(HttpServletRequest request) throws ParseException {
        String book_name = request.getParameter("bookName");
        String book_author = request.getParameter("bookAuthor");
        String str_date = request.getParameter("bookDate");

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date book_date = sdf.parse(str_date);
        //1.设置日期的格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //2.将字符串转换成LocalDate格式
        LocalDate localDate = LocalDate.parse(str_date,dateTimeFormatter);
        //3.获取默认的系统时区
        ZoneId zoneId = ZoneId.systemDefault();
        //4.将LocalDate对象转换为本地时间
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(zoneId);
        //5.将LocalDate对象转换成Date格式
        Date book_date = Date.from(zonedDateTime.toInstant());

        Double book_price = Double.parseDouble(request.getParameter("bookPrice"));

        Book book = new Book(null,book_name,book_author,book_date,book_price);
        int flag = bookService.insertBook(book);

        return flag>0?"true":"false";
    }
}
